package com.mar.quarkus.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.json.Json;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.util.Optional;

/**
 * Description: 异常拦截$ .<br>
 *
 * @author m-xy
 *     Created By 2020/4/27 15:05
 */
@Provider
public class ErrorMapper implements ExceptionMapper<Exception> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ErrorMapper.class);

    @Override
    public Response toResponse(Exception exception) {
        LOGGER.error("系统响应异常", exception);
        int code = 400;
        if (exception instanceof WebApplicationException) {
            code = ((WebApplicationException) exception).getResponse().getStatus();
        }
        return Response.status(code)
            .entity(
                Json.createObjectBuilder()
                    .add("message", Optional.ofNullable(exception.getMessage()).orElse("系统异常"))
                    .add("code", code)
                    .build()
            )
            .build();
    }
}
